package com.yym.sina.weibo;

import java.io.IOException;
import java.util.Collections;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.cib.yym.homepage.common.CacheManager;
import com.cib.yym.homepage.common.CacheManagerFactory;

public class OAuthServlet extends HttpServlet {
		
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		String code = req.getParameter("code");
		
		OAuthTokenGenerator oauth = new OAuthTokenGenerator();
		String s = oauth.getUserAccessToken(code);
		JSONObject temp = null; 
		String accessToken = null;
		String uid = null;
		try {
			temp = new JSONObject(s);
			if (temp instanceof JSONObject)
			{
				accessToken = temp.optString("access_token");
				uid = temp.optString("uid");
				
				CacheManager cache = CacheManagerFactory.getCacheManager();            
	            cache.updateCache(CacheManager.MAP_WEIBO_CONFIG, "accessToken", accessToken);
	            
				//TODO
				/**
				 * 表示Weibo用户认证成功
				 * 1. 如果用户在系统中已经有关联的siteuser账号，则将其保存到session中，认为是已登录用户
				 * 2. 如果用户在系统中首次认证通过用户，则提示输入本系统id及用户显示名。
				 */
			}else
			{
				//TODO
				/**
				 * 认证失败，提示重新认证
				 * 理论上不应该发生
				 */
			}
		} catch (JSONException e1) {			
			e1.printStackTrace();
		}
		
		//resp.getWriter().println("result="+s);
        resp.sendRedirect(req.getContextPath()+"/signinSuccess.jsp");
		//TODO 转入dashboard
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		this.doGet(req, resp);
	}
}
